﻿using System;
using System.Linq;
using MediaStreamer.Containers;
using Org.Flowertwig.Media.Information.Services;
using Raven.Client.Indexes;

namespace MediaStreamer
{
    class Program
    {
        const string resetCommand = "/reset";
        const string installCommand = "/install";

        static void Main(string[] args)
        {
            // If we have no arguments, lets start service
            if (args.Length == 0)
            {
                var server = new Server(80);
                server.Start();

                Console.Read();
                server.Stop();

            }else
            {
                foreach (var arg in args)
                {
                    if (arg.StartsWith(resetCommand, StringComparison.CurrentCultureIgnoreCase))
                    {
                        Reset();
                    }
                    else if (arg.StartsWith(installCommand, StringComparison.CurrentCultureIgnoreCase))
                    {
                        Install();
                    }
                    else
                    {
                        Console.WriteLine("Unknown command: " + arg);
                    }
                }
            }
        }

        private static void Install()
        {
            Console.WriteLine("# Installing as service");

            ProjectInstaller p = new ProjectInstaller();
            var info = new System.Collections.Hashtable();
            p.Install(info);

            Console.WriteLine("# Installation complete");
        }

        private static void Reset()
        {
            Console.WriteLine("# Reset - Creating Index");
            Storage.EnsureIndex("Navigations/DeleteIndexes",
                                      new IndexDefinitionBuilder<Navigation>
                                      {
                                          Map =
                                              myClasses =>
                                              from myClass in myClasses
                                              select new
                                              {
                                                  Id = myClass.Id
                                              }
                                      });
            Console.WriteLine("# Reset - Removing items matching index");
            Storage.DeleteAllItemsOfType<Navigation>("Navigations/DeleteIndexes");
            PageHandler.Reset();
            Console.WriteLine("# Reset - Items has been removed");
        }
    }
}
